<template>
  <div id="teamPage">
    <van-search v-model="searchText" placeholder="请输入搜索关键词" @search="onSearch" />
    <van-button class="add-button" type="primary" icon="plus" @click="toAddTeam" />
    <van-tabs v-model:active="active" @change="onTabChange">
      <van-tab title="公开" name="public">
        <template #title>
          <van-icon name="eye-o" size="14px" />
          公开
        </template>
      </van-tab>
      <van-tab title="加密" name="private">
        <template #title>
          <van-icon name="lock" size="14px" />
          加密
        </template>
      </van-tab>
    </van-tabs>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <team-card-list :team-list="teamList" />
      <van-empty v-if="teamList?.length < 1" desc ription="数据为空" />
    </van-pull-refresh>
    <van-back-top class="van-back-top" bottom="15vh" />
  </div>
  <div style="text-align: center;
                padding: 20px 20px;
                column-span: all;"
  >
    <van-button type="primary" size="small" @click="loadClick">点击加载更多</van-button>
  </div>

</template>

<script setup lang="ts">
import {useRouter} from "vue-router";
import TeamCardList from "../components/TeamCardList.vue";
import {onMounted, ref} from "vue";
import myAxios from "../plugins/myAxios";
import {showFailToast, showLoadingToast, showSuccessToast, showToast} from "vant";
import {UserType} from "../models/user";

const router = useRouter();

const teamList = ref([]);

const active = ref('public');
const searchText = ref('');
//下拉刷新
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const pageNum = ref(2);

//分页加载
const pageNumByPublic = ref(2);
const pageNumByPrivate = ref(2);

//获取当前 tab栏的值
const tabName = ref<String>('public');

/**
 * 点击加载更多
 */
const loadClick = async () => {
  let userListData;
  //匹配模式，根据标签匹配用户
  if (tabName.value === 'public'){
    showLoadingToast({
      message: '加载中',
      forbidClick: true
    })
    userListData = await myAxios.get('/team/list/page', {
      params: {
        pageSize: 5,
        pageNum: pageNumByPublic.value++,
        status: 0
      },
    })
        .then(function (response) {
          console.log('/team/list/page success', response);
          showSuccessToast('加载成功');
          return response?.data?.records; //返回数据 ?.可选链操作符，避免数据为 null
        })
        .catch(function (error) {
          console.log('/team/list/page error', error);
          showFailToast('加载失败');
        })
  }else if (tabName.value === 'private') {
    showLoadingToast({
      message: '加载中',
      forbidClick: true
    })
    userListData = await myAxios.get('/team/list/page', {
      params: {
        pageSize: 5,
        pageNum: pageNumByPrivate.value++,
        status: 2
      },
    })
        .then(function (response) {
          console.log('/team/list/page success', response);
          showSuccessToast('加载成功');
          return response?.data?.records; //返回数据 ?.可选链操作符，避免数据为 null
        })
        .catch(function (error) {
          console.log('/team/list/page error', error);
          showFailToast('加载失败');
        })
  }
  // if (userListData) {
    // userListData.forEach((user: UserType) => {
    //   if (user.tags) {
    //     user.tags = JSON.parse(user.tags);
    //   }
    // })
    // userListData.value = userListData.value.concat(userListData.data?.records);
    teamList.value = teamList.value.concat(userListData);
    console.log("list== " + teamList.value.length);
  // }
}

/**
 * 点击加载更多
 */
// const loadClick = async () => {
//   const res = await myAxios.get("/team/list/page", {
//     params:{
//       pageSize: 5,
//       pageNum: pageNum.value++
//     },
//   });
//   // const res = onTabChange(tabName);
//   if (res?.code === 0){
//       teamList.value = teamList.value.concat(res.data?.records);
//     console.log("111== " + teamList);
//     // teamList.value = res.data?.records;
//   }else {
//     showFailToast("队伍加载失败，请刷新重试");
//   }
// };

/**
 * 加载
 */
const onLoad = (tabName) => {

  setTimeout(() => {
    if (refreshing.value) {
      refreshing.value = false;
    }
    // onTabChange(tabName);
    loading.value = false;
    //console.log('tabName===' + tabName.value)
    onTabChange(tabName);
  }, 1000);
  pageNum.value = 2;
};

/**
 * 下拉刷新
 */
const onRefresh = (tabName) => {
  // 清空列表数据
  finished.value = false;
  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true;
  onLoad(tabName);
};

/**
 * 切换查询状态
 * @param name
 */
const onTabChange = (name = tabName.value) => {
  //查公开队伍
  if (name === 'public'){
    tabName.value = name;
    console.log('public===' + tabName.value)
    loadListTeam(searchText.value, 0);
    pageNumByPublic.value = 2;
  }else if (name === 'private') {
    //查加密队伍
    tabName.value = name;
    console.log('private===' + tabName.value)
    loadListTeam(searchText.value, 2);
    pageNumByPrivate.value = 2;
  }else {
    console.log('name===' + name)
  }
};

/**
 *
 * @param val
 * @param status
 */
// const listTeam = async (val = '', status = 0) => {
//   const res = await myAxios.get("/team/list/page", {
//     params:{
//       searchText: val,
//       pageSize: 5,
//       pageNum: 1,
//       status: status
//     },
//   });
//   if (res?.code === 0){
//     teamList.value = res.data?.records;
//   }else {
//     showFailToast("队伍加载失败，请刷新重试");
//   }
// }

/**
 * 加载、搜索队伍
 * @param val
 * @param status
 */
const loadListTeam = async (val = '', status = 0) => {
  const res = await myAxios.get("/team/list/page", {
    params:{
      searchText: val,
      pageSize: 5,
      pageNum: 1,
      status: status
    },
  });
  if (res?.code === 0){
    teamList.value = res.data?.records;
    console.log("搜成功= " + val)
  }else {
    showFailToast("队伍加载失败，请刷新重试");
  }
}

onMounted(() => {
  loadListTeam();
})

/**
 * 搜索
 * @param val
 * @param name
 */
const onSearch = (val, name = tabName.value) => {
  if (name === 'public'){
    console.log("sta= ", tabName.value)
    loadListTeam(val, 0);
    val=searchText;
  }else if (name === 'private'){
    console.log("sta= ", tabName.value)
    loadListTeam(val, 2);
    val = searchText;
  }
}

//跳转到加入队伍页
const toAddTeam =() =>{
  router.push({
    path:"/team/add"
  })
}
</script>

<style scoped>

</style>